package servlet;
import Util.*;
import factory.impl.WebAppHandlerFactory;
import handler.DefaultHandler;
import interceprtor.InterceptorChain;
import view.OtherView;
import view.ViewResult;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Dispacther extends HttpServlet {
    private HandlerMaping handlerMaping;
    public static final String DEFAULT="DEFAULT";
    public static final String HANDLER="HANDLER";
    @Override
    public void init(ServletConfig config) throws ServletException {
        initmaping(config);
        initHandler(config);
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        initActionContext(req,resp);
        try {
            InterceptorChain chain = handlerMaping.find(req);
            if(chain.getDefinition()==null){
                new DefaultHandler().handler(req,resp);
            }else{
                Object result = chain.execute();
                result(result);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    //视图结果集
    private void result(Object result){
        if (result==null){
            return;
        }else if (result instanceof ViewResult){
            ((ViewResult) result).execute();
        }else{
            OtherView view=new OtherView(result);
            view.execute();
        }
    }
    //初始化map
    private void initmaping(ServletConfig config){
        Map<String, HandlerDefinition> map = HandlerDefinitionparse.parse();
        config.getServletContext().setAttribute(DEFAULT,map);
        handlerMaping=new HandlerMaping();
    }
    private void initHandler(ServletConfig config){
        Object attribute = config.getServletContext().getAttribute(Dispacther.HANDLER);;
        if (attribute==null){
            config.getServletContext().setAttribute(HANDLER,new WebAppHandlerFactory());
        }
    }
    //初始化ActionContext
    private void initActionContext(HttpServletRequest request,HttpServletResponse response){
        ActionContext.getContext().setRequest(request);
        ActionContext.getContext().setResponse(response);
    }
}
